import json
import os

# 输出路径
OUTPUT_HTML = os.path.join(os.path.dirname(__file__), "..", "dashboard.html")
REPORT_JSON = os.path.join(os.path.dirname(__file__), "report.json")

def build_dashboard():
    # 读取 report.json
    with open(REPORT_JSON, "r", encoding="utf-8") as f:
        report = json.load(f)

    # 写入 dashboard.html
    with open(OUTPUT_HTML, "w", encoding="utf-8") as f:
        f.write(f"""
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>AI股票预测系统</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
</head>
<body>
  <nav class="navbar navbar-dark bg-dark">
    <span class="navbar-brand mb-0 h1 ms-3">📈 AI股票预测系统</span>
  </nav>
  <div class="container-fluid mt-3">
    <div class="row">
      <!-- 左侧交易品种列表 -->
      <div class="col-md-3">
        <div class="list-group" id="symbols-list"></div>
      </div>
      <!-- 右侧图表 -->
      <div class="col-md-9">
        <div id="chart" style="width:100%;height:600px;"></div>
      </div>
    </div>
  </div>

  <script>
    // 把 Python 数据传到 JS
    const symbols = {json.dumps(report, ensure_ascii=False)};

    const list = document.getElementById("symbols-list");
    symbols.forEach((s,i)=>{
      const item = document.createElement("a");
      item.href = "#";
      item.className = "list-group-item list-group-item-action";
      item.innerHTML = `<span>${{s.name}}<br>
                        <small>交易 ${{s.trades}} 次 | 胜率 ${{s.winrate}}%</small></span>
                        <span style="float:right;color:${{s.profit>=0?"green":"red"}};">
                        ${{s.profit.toFixed(2)}}%</span>`;
      item.onclick = () => loadChart(s);
      list.appendChild(item);
    });

    function loadChart(s) {{
      const chart = echarts.init(document.getElementById("chart"));
      const option = {{
        title: {{ text: s.name + " 回测图表" }},
        tooltip: {{ trigger: 'axis' }},
        xAxis: {{ type: 'category', data: s.dates }},
        yAxis: {{ type: 'value' }},
        series: [
          {{
            data: s.values,
            type: 'line',
            smooth: true
          }}
        ]
      }};
      chart.setOption(option);
    }}

    // 默认加载第一个
    if(symbols.length > 0) {{
      loadChart(symbols[0]);
    }}
  </script>
</body>
</html>
        """)

    print(f"✅ Dashboard saved to {OUTPUT_HTML}")

if __name__ == "__main__":
    build_dashboard()
